import { BuildHook } from "../@types/packages/builder/@types";

const PACKAGE_NAME = 'my-build-package';

export const throwError: BuildHook.throwError = true;

export const load: BuildHook.load = async function() {
    console.log(PACKAGE_NAME,load);
};

export const onBeforeBuild: BuildHook.onBeforeBuild = async function(options) {
    // Todo some thing
    console.log(PACKAGE_NAME,'onBeforeBuild');
};

export const onBeforeCompressSettings: BuildHook.onBeforeCompressSettings = async function(options, result) {
    // Todo some thing
    console.log(PACKAGE_NAME,'onBeforeCompressSettings');
};

export const onAfterCompressSettings: BuildHook.onAfterCompressSettings = async function(options, result) {
    // Todo some thing
    console.log(PACKAGE_NAME, 'onAfterCompressSettings');
};

export const onAfterBuild: BuildHook.onAfterBuild = async function(options, result) {
    console.log(PACKAGE_NAME, 'onAfterBuild');

    // 构建后改下文件application.js文件里面的内容
    let appPath = result.paths.applicationJS

    console.log("test appPath", appPath)

    let fs = require('fs')
    fs.readFile(appPath, 'utf8', function (err : any, data : any) {
        if(err) {
            console.error(err)
            return
        }
        let newData = data
        let replaceData = "cc.game.onStart = onGameStarted.bind(null, cc); \/\/我们自己的" + "\r\n\t\t\t\t\t\t\t" + "onGameStarted(cc)\/\/我们自己的"
        let replaceData2 = "cc = engine;" + "\r\n\t\t\t\t\t\t" + "setLoadingDisplay() \/\/在默认代码插入我们这行代码"
        newData = newData.replace("return cc.game.run();", replaceData)
        newData = newData.replace("cc = engine;", replaceData2)


        fs.writeFile(appPath, newData, 'utf8', function (err : any) {
            if (err) {
                console.error(err);
                return;
              }
              console.log('app File saved successfully.');
        })

    })

};

export const unload: BuildHook.unload = async function() {
    console.log(PACKAGE_NAME, 'unload');
};